import ScrollBarLayout from '@/components/ScrollBarLayout';
import Cls from 'classnames';
import pageStyles from '@/common/pageLayout.less';
import { useContext, useEffect, useMemo, useState } from 'react';
import { DescriptionsType } from '@/components/DescriptionsType';
import { getLoadMapList, getTenantID } from '@/utils';
import { connect, history } from 'umi';
import { Col, Form, Row, Spin, message, Tabs, Button, Space, Modal } from 'antd';
import { MyAssetListManageAPI } from '../common/type';
import { SaveOutlined, CloseCircleOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { ILoadMapTypeAll } from '@/common';
import { addAssetMaterielService, detailAssetMaterielService, editAssetMaterielService, getAssetClassService } from '../services';
import moment from 'moment';
import {
  getCarUpdateConfig,
  getEquipmentFurnitureUpdateConfig,
  getHouseUpdateConfig,
  getInvestUpdateConfig,
  getInvisibleUpdateConfig,
  getLeaseHouseUpdateConfig,
  getLeaseLandUpdateConfig,
  getOtherUpdateConfig,
  getProjectUpdateConfig,
  getStockpileUpdateConfig,
} from '../mconfig';
import { filterTimeProperties, submitTimeProperties } from '../../Acommon';
import LifeCycleView from './LifeCycleView';
import UserInfoDrawer from './UserInfoDrawer';
import _ from 'lodash';

const AcceptUpdateView: React.FC<any> = ({ curRes, locationProps }: MyAssetListManageAPI.AcceptRouterDataType) => {
  /** 样式根目录 */
  const styleFixCls = 'contract-styfixcls-';

  /**  获取数据字典 */
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.AVERAGE_LIFE_METHOD}`, //折旧方法
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`, //计量单位
    `${getTenantID()}${ILoadMapTypeAll.ASSET_PURCHASE_TYPE}`, //采购方式
    `${getTenantID()}${ILoadMapTypeAll.ASSET_ACQUIRE_TYPE}`, //取得形式
    `${getTenantID()}${ILoadMapTypeAll.ASSET_VALUE_TYPE}`, //价值类型
    `${getTenantID()}${ILoadMapTypeAll.ASSET_CAR_TYPE}`, //车辆类型
    `${getTenantID()}${ILoadMapTypeAll.ASSET_USE_TYPE}`, //使用权类型
    `${getTenantID()}${ILoadMapTypeAll.MATERIEL_STATUS}`, //材料状态
    `${getTenantID()}${ILoadMapTypeAll.ASSET_STATUS}`, //资产状态
    `${getTenantID()}${ILoadMapTypeAll.ASSET_AREA}`, // 存放区域
    `${getTenantID()}${ILoadMapTypeAll.ASSET_EQUITY}`, // 产权
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_TYPE}`, // 资产分类
    `${getTenantID()}${ILoadMapTypeAll.ASSET_LIFE_METHOD_STATUS}`, // 折旧/摊销状态
    `${getTenantID()}${ILoadMapTypeAll.ASSET_USED}`, // 资产用途
    `${getTenantID()}${ILoadMapTypeAll.ASSET_ORGANIZATION_STATUS}`, // 资产编制情况
    `${getTenantID()}${ILoadMapTypeAll.ASSET_ENTRY_STATE}`, // 财务入账状态
    `${getTenantID()}${ILoadMapTypeAll.ASSET_DENSE_STATE}`, // 定密状态
    `${getTenantID()}${ILoadMapTypeAll.ASSET_VEHICLE_EXHAUST_VOLUME}`, // 车辆排气量
    `${getTenantID()}${ILoadMapTypeAll.ASSET_RESPONSIBILITY}`, // 使用责任主体
    `${getTenantID()}${ILoadMapTypeAll.ASSET_APPROVEDBY}`, // 配置批准单位
    `${getTenantID()}${ILoadMapTypeAll.LEDGER_ACCOUNT}`, // 单位会计科目
  ]);

  /** 共通表单数据 */
  const [bothForm] = Form.useForm();

  /** 材料表单数据 */
  // const [assetLandForm] = Form.useForm(); // 土地
  // const [assetHouseForm] = Form.useForm(); // 房屋
  const [assetCarForm] = Form.useForm(); // 车辆
  const [assetEquipmentFurnitureForm] = Form.useForm(); // 设备及家具
  const [assetOtherForm] = Form.useForm(); // 其他固定资产
  // const [assetInvisibleForm] = Form.useForm(); // 专利及信息数据等无形资产
  // const [assetProjectForm] = Form.useForm(); // 在建工程
  // const [assetLeaseLandForm] = Form.useForm(); // 租赁土地
  // const [assetLeaseHouseForm] = Form.useForm(); // 租赁房屋
  // const [assetStockpileForm] = Form.useForm(); // 政府储备物资
  // const [assetInvestForm] = Form.useForm(); // 长期投资

  /** 当前材料类型 */
  const [selectAssetType, setSelectAssetType] = useState<string>('100124021002');

  /** 当前详情数据 */
  const [data, setData] = useState<any>({
    scrapRate: 0,
    depreciationMoney: 0,
    providedDepreciation: 0,
  });

  /** 处理时间之前的数据 */
  const [userInfo, setUserInfo] = useState<any>({});

  /** 是否显示仓库资管员信息抽屉 */
  const [isShowDetail, setIsShowDetail] = useState<Record<string, any>>({
    isShow: false,
    recordObj: data,
  });

  /** 获取资产类别回调 */
  const getAssetClassCallback = (res: Record<string, any>) => {
    if (res && res?.msgFlag && res?.obj) {
      /** 更新表单类型 */
      setSelectAssetType(res?.obj);
    }
  };

  /** 编辑资产回调 */
  const editAssetMaterielCallback = (res: Record<string, any>) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      history.push({
        pathname: '/assetController/manage',
        state: {
          delRouterNameSource: history.location.pathname,
        },
      });
    } else {
      message.error(res?.msg);
    }
  };

  /** 获取资产类别 */
  const { getAssetClassRun, getAssetClassLoading } = getAssetClassService(getAssetClassCallback);

  /** 编辑资产 */
  const { editAssetMaterielRun, editAssetMaterielLoading } = editAssetMaterielService(editAssetMaterielCallback);

  const changeAssetType = (value: string, node?: any) => {
    getAssetClassRun(value);
    /** 清空表单 */
    // assetCarForm?.setFieldsValue({});
    // assetEquipmentFurnitureForm?.setFieldsValue({});
    // assetOtherForm?.setFieldsValue({});
    // selectAssetType === '100124021000' && assetLandForm?.setFieldsValue({});
    // selectAssetType === '100124021001' && assetHouseForm?.setFieldsValue({});
    // selectAssetType === '100124021002' && assetCarForm?.setFieldsValue({});
    // selectAssetType === '100124021003' && assetEquipmentFurnitureForm?.setFieldsValue({});
    // selectAssetType === '100124021004' && assetOtherForm?.setFieldsValue({});
    // selectAssetType === '100124021005' && assetInvisibleForm?.setFieldsValue({});
    // selectAssetType === '100124021006' && assetProjectForm?.setFieldsValue({});
    // selectAssetType === '100124021007' && assetLeaseLandForm?.setFieldsValue({});
    // selectAssetType === '100124021008' && assetLeaseHouseForm?.setFieldsValue({});
    // selectAssetType === '100124021009' && assetStockpileForm?.setFieldsValue({});
    // selectAssetType === '100124021010' && assetInvestForm?.setFieldsValue({});
  };

  /** 获取表单配置
   *  @record   当前项
   *  @pageType  当前的页面类型
   */
  /** 土地 */
  // const { landConfig, landMethods } = getLandUpdateConfig({
  //   pageType: locationProps?.state?.pageType ? locationProps?.state?.pageType : '',
  //   record: data,
  //   assetLandForm,
  //   loadMapInfo,
  //   mapLoading,
  //   changeAssetType,
  // });
  /** 房屋 */
  // const { houseConfig, houseMethods } = getHouseUpdateConfig({
  //   pageType: locationProps?.state?.pageType ? locationProps?.state?.pageType : '',
  //   record: data,
  //   assetHouseForm,
  //   loadMapInfo,
  //   mapLoading,
  //   changeAssetType,
  // });
  /** 车辆 */
  const { carConfig, carMethods } = getCarUpdateConfig({
    pageType: locationProps?.state?.pageType ? locationProps?.state?.pageType : '',
    record: data,
    assetCarForm,
    loadMapInfo,
    mapLoading,
    changeAssetType,
    selectAssetType,
  });
  /** 设备及家具 */
  const { equipmentFurnitureConfig, equipmentFurnitureMethods } = getEquipmentFurnitureUpdateConfig({
    pageType: locationProps?.state?.pageType ? locationProps?.state?.pageType : '',
    record: data,
    assetEquipmentFurnitureForm,
    loadMapInfo,
    mapLoading,
    changeAssetType,
    selectAssetType,
  });
  /** 其他固定资产 */
  const { otherConfig, otherMethods } = getOtherUpdateConfig({
    pageType: locationProps?.state?.pageType ? locationProps?.state?.pageType : '',
    record: data,
    assetOtherForm,
    mapLoading,
    loadMapInfo,
    changeAssetType,
    selectAssetType,
  });
  /** 专利及信息数据等无形资产 */
  // const { invisibleConfig, invisibleMethods } = getInvisibleUpdateConfig({
  //   pageType: locationProps?.state?.pageType ? locationProps?.state?.pageType : '',
  //   record: data,
  //   assetInvisibleForm,
  //   mapLoading,
  //   loadMapInfo,
  //   changeAssetType,
  // });
  /** 在建工程 */
  // const { projectConfig, projectMethods } = getProjectUpdateConfig({
  //   pageType: locationProps?.state?.pageType ? locationProps?.state?.pageType : '',
  //   record: data,
  //   assetProjectForm,
  //   mapLoading,
  //   loadMapInfo,
  //   changeAssetType,
  // });
  /** 租赁土地 */
  // const { leaseLandConfig, leaseLandMethods } = getLeaseLandUpdateConfig({
  //   pageType: locationProps?.state?.pageType ? locationProps?.state?.pageType : '',
  //   record: data,
  //   assetLeaseLandForm,
  //   mapLoading,
  //   loadMapInfo,
  //   changeAssetType,
  // });
  /** 租赁房屋 */
  // const { leaseHouseConfig, leaseHouseMethods } = getLeaseHouseUpdateConfig({
  //   pageType: locationProps?.state?.pageType ? locationProps?.state?.pageType : '',
  //   record: data,
  //   assetLeaseHouseForm,
  //   mapLoading,
  //   loadMapInfo,
  //   changeAssetType,
  // });
  /** 政府储备物资 */
  // const { stockpileConfig, stockpileMethods } = getStockpileUpdateConfig({
  //   pageType: locationProps?.state?.pageType ? locationProps?.state?.pageType : '',
  //   record: data,
  //   assetStockpileForm,
  //   mapLoading,
  //   loadMapInfo,
  //   changeAssetType,
  // });
  /** 长期投资 */
  // const { investConfig, investMethods } = getInvestUpdateConfig({
  //   pageType: locationProps?.state?.pageType ? locationProps?.state?.pageType : '',
  //   record: data,
  //   assetInvestForm,
  //   loadMapInfo,
  //   mapLoading,
  //   changeAssetType,
  // });

  /** 查看详情回调 */
  const detailCallback = (res: any) => {
    if (res && res?.msgFlag) {
      setUserInfo(res.obj);
      changeAssetType(res.obj.assetClass);
      let obj: Record<string, any> = {};
      if (locationProps?.state?.pageType !== 'detail') {
        // 处理时间格式
        obj = filterTimeProperties(res.obj);
      } else {
        if (res.obj.target && typeof res.obj.target === 'object' && Object.keys(res.obj.target).length !== 0) {
          // 将对象中target对象中的内容平铺
          obj = { ...res.obj.target, ...res.obj };
          delete obj.target;
        } else {
          obj = { ...res.obj };
        }
      }
      setData(obj);
      message.success(res?.msg);
    } else {
      message.error(res?.msg);
    }
  };

  /** 查看详情接口 */
  const { detailAssetMaterielLoading, detailAssetMaterielRun } = detailAssetMaterielService(detailCallback);

  /** 暂存 */
  const submitForm = (dataFormConfig: any) => {
    dataFormConfig.form.validateFields()?.then((values: any) => {
      // 校验 资产原值=财政拨款+非财政拨款
      const fiscalAppropriationNum = values.fiscalAppropriation; // 财政拨款
      const noFiscalAppropriationNum = values.noFiscalAppropriation; // 非财政拨款
      const totalValueNum = values.totalValue; // 资产原值
      if (
        values?.entryState != `${getTenantID()}${ILoadMapTypeAll.ASSET_ENTRY_STATE}1002` &&
        _.round(totalValueNum, 2) !== _.add(_.round(fiscalAppropriationNum), _.round(noFiscalAppropriationNum))
      ) {
        return message.warning('财政拨款、非财政拨款相加不等于资产原值，请修改后保存！');
      }

      let obj: any = JSON.parse(JSON.stringify(values));
      let timeObj: any = submitTimeProperties(obj);
      let dataObj: any = submitTimeProperties(data);
      obj.beforeJson = JSON.stringify(userInfo);
      obj = { ...dataObj, ...timeObj };
      obj.target = { ...timeObj };
      obj.target.id = obj.targetId;
      // delete obj.targetId;
      editAssetMaterielRun(obj);
    });
  };

  /** 关闭当前页 */
  const handleClose = () => {
    history.push({
      pathname: '/assetController/manage',
      state: {
        delRouterNameSource: history.location.pathname,
      },
    });
  };

  useEffect(() => {
    if (locationProps?.state?.id) {
      detailAssetMaterielRun({ id: locationProps?.state?.id });
    } else {
      changeAssetType(locationProps?.state?.record ? locationProps?.state?.record.assetType : '100124021000');
    }
  }, []);

  /** 申请页ref */
  const { confirm } = Modal;

  const closeCurrent = () => {
    confirm({
      title: '关闭',
      icon: <QuestionCircleOutlined />,
      content: '确定要关闭当前页吗？',
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      onOk() {
        history.push({
          pathname: locationProps?.state?.returnPathName,
          state: {
            delRouterNameSource: history.location.pathname, //必传,要删除的路由名称
            returnPathName: locationProps?.state?.returnPathName,
          },
        });
      },
      onCancel() {},
    });
  };

  return (
    <>
      <Spin spinning={detailAssetMaterielLoading || editAssetMaterielLoading || getAssetClassLoading}>
        <Row gutter={[8, 8]} className={`${styleFixCls}row`}>
          <Col span={24} className={`${styleFixCls}row-col`} style={{ position: 'relative' }}>
            <Tabs
              className={pageStyles['commonTabs']}
              type="card"
              onChange={(activeKey: string) => {}}
              items={[
                {
                  label: '资产卡片',
                  key: '001',
                  children: (
                    <>
                      <div className="commonTabsBodyDom">
                        <div className={Cls('tabsBodyInfoDom', `${styleFixCls}updateFormBox`)}>
                          <ScrollBarLayout style={{ padding: '5px 20px' }}>
                            <Row>
                              <Col span={24}>
                                {/* <DescriptionsType config={bothConfig} key={0} /> */}
                                {/* {selectAssetType === '100124021000' && <DescriptionsType config={landConfig} key={1} />}
                                {selectAssetType === '100124021001' && <DescriptionsType config={houseConfig} key={2} />} */}
                                {selectAssetType === '100124021002' && <DescriptionsType config={carConfig} key={3} />}
                                {selectAssetType === '100124021003' && <DescriptionsType config={equipmentFurnitureConfig} key={4} />}
                                {selectAssetType === '100124021004' && <DescriptionsType config={otherConfig} key={5} />}
                                {/* {selectAssetType === '100124021005' && <DescriptionsType config={invisibleConfig} key={6} />}
                                {selectAssetType === '100124021006' && <DescriptionsType config={projectConfig} key={7} />}
                                {selectAssetType === '100124021007' && <DescriptionsType config={leaseLandConfig} key={8} />}
                                {selectAssetType === '100124021008' && <DescriptionsType config={leaseHouseConfig} key={9} />}
                                {selectAssetType === '100124021009' && <DescriptionsType config={stockpileConfig} key={10} />}
                                {selectAssetType === '100124021010' && <DescriptionsType config={investConfig} key={11} />} */}
                              </Col>
                            </Row>
                          </ScrollBarLayout>
                        </div>
                        <div className="tabsBodyBottomBtn">
                          <Space>
                            {locationProps?.state?.pageType !== 'detail' && locationProps?.state?.pageType !== 'hidden' && (
                              <Button
                                type={'primary'}
                                // icon={<SaveOutlined />}
                                disabled={locationProps?.state?.pageType === 'detail' || locationProps?.state?.pageType === 'hidden'}
                                loading={detailAssetMaterielLoading}
                                onClick={() => {
                                  selectAssetType === '100124021002' && submitForm(carConfig);
                                  selectAssetType === '100124021003' && submitForm(equipmentFurnitureConfig);
                                  selectAssetType === '100124021004' && submitForm(otherConfig);
                                }}
                              >
                                保存
                              </Button>
                            )}
                            <>
                              <Button
                                danger
                                // type={'primary'}
                                // icon={<CloseCircleOutlined />}
                                loading={detailAssetMaterielLoading}
                                onClick={closeCurrent}
                              >
                                关闭
                              </Button>
                            </>
                          </Space>
                        </div>
                      </div>
                    </>
                  ),
                },
                {
                  label: '全生命周期记录',
                  key: '002',
                  children: (
                    <>
                      <div className="commonTabsBodyDom">
                        <div className={Cls('tabsBodyInfoDom', `${styleFixCls}updateFormBox`)}>
                          <ScrollBarLayout style={{ padding: '5px 20px' }}>
                            <LifeCycleView id={locationProps?.state?.id} curRes={curRes}></LifeCycleView>
                          </ScrollBarLayout>
                        </div>
                      </div>
                    </>
                  ),
                },
              ]}
              destroyInactiveTabPane={true}
            />

            <div className="tabsBodyBottomBtn" style={{ position: 'absolute', top: 5, right: 8 }}>
              <Space>
                <Button
                  type={'primary'}
                  // icon={<SaveOutlined />}
                  onClick={() => {
                    setIsShowDetail({
                      isShow: true,
                      recordObj: data,
                    });
                  }}
                >
                  更多
                </Button>
              </Space>
            </div>
            {/* 查看详情抽屉 */}
            <UserInfoDrawer
              curRes={curRes}
              onClose={() => {
                setIsShowDetail({
                  isShow: false,
                  // recordObj: {},
                });
              }}
              isShowDetail={isShowDetail?.isShow}
              recordObj={userInfo ? userInfo : {}}
              reloadManage={() => {}}
            />
          </Col>
        </Row>
      </Spin>
    </>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
  navTab,
}))(AcceptUpdateView);
